/*
 * @file: menu utils
 */

export const handlerRouterConfig = config => {
    return config.map((v, i) => {
        v.key = `sub${i}`;
        return v;
    });
};

export const getOpenKeys = (config, props) => {
    // 仅支持二级菜单打开 三级及以下不支持
    const {location} = props;
    let openKey = '';
    config.some(item => {
        if (!item.children && item.path === location.pathname) {
            openKey = item.key;
            return true;
        }
        if (item.children) {
            item.children.some(value => {
                if (value.path === location.pathname || location.pathname.indexOf(value.path) >= 0) {
                    openKey = item.key;
                    return true;
                } else {
                    return false;
                }
            });
        }
        return false;
    });
    return openKey;
};

export const getSelectedKey = (config, props) => {
    // 仅支持二级菜单打开 三级及以下不支持
    const pathname = props.location.pathname;
    let selectedKey = '';
    config.some(item => {
        if (pathname.indexOf(item.path) >= 0) {
            selectedKey = item.path;
            return true;
        }
        if (item.children) {
            item.children.some(value => {
                if (pathname.indexOf(value.path) >= 0) {
                    selectedKey = value.path;
                    return true;
                } else {
                    return false;
                }
            });
        }
        return false;
    });
    return selectedKey;
};

export const isAuthority = (systemAuthority, userAuthority) => {
    /**
     * @params systemAuthority 系统权限数组 [1, 2, 3 ,4];
     * @params userAuthority   用户权限 1 || 2 || 3 || 4;
     * @return true 有权限 false 无权限
     */
    return !!systemAuthority ? systemAuthority.includes(userAuthority) : true;
};

export const isAuthority403 = (props, config) => {
    /**
     * 判断用户是否有当前页面的权限 过滤直接从 HTTP地址进入的用户
     * @params props
     * @params config menu配置
     * @return userAuthority 用户权限
     */
    const pathname = props.location.pathname;
    const userAuthority = props.global.authority;
    let result = false;
    config.some(item => {
        if (pathname.indexOf(item.path) >= 0) {
            result = !isAuthority(item.authority, userAuthority);
            return true;
        }
        if (item.children) {
            item.children.some(value => {
                if (pathname.indexOf(value.path) >= 0) {
                    result = !isAuthority(value.authority, userAuthority);
                    return true;
                } else {
                    return false;
                }
            });
        }
        return false;
    });
    return pathname.indexOf('/main/403') >= 0 ? true : result;
};
